//
//  CircleListMainViewModel.m
//  RACExample
//
//  Created by 山刘 on 2020/6/3.
//  Copyright © 2020 山刘. All rights reserved.
//

#import "CircleListMainViewModel.h"
#import "DouBanTheatersModel.h"

@interface CircleListMainViewModel()
@property (nonatomic, strong) HttpManager *httpManager;
@property (nonatomic, strong,readwrite) NSArray<CircleListMainViewCellViewModel*> *dataArray;
@end

@implementation CircleListMainViewModel
#pragma mark - init
-(instancetype)init{
    if (self = [super init]) {
        [self racInit];
    }
    return self;
}
#pragma mark - business
- (void)racInit {
    // 初始化 RACCommand ，并发起网络请求。
    _refreshDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            // 网络请求
            NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
            parameters[@"apikey"] = @"0df993c66c0c636e29ecbb5344252a4a";
            [self.httpManager requestNetworkDataWithUrlString:@"/v2/movie/in_theaters" Params:parameters completed:^(id  _Nonnull response, NSError * _Nonnull error) {
                if (error) {
//                    NSLog(@"refreshDataCommand subscriber sendError");
                    [subscriber sendError:error];
                }else{
//                    NSLog(@"refreshDataCommand subscriber sendNext");
                    [subscriber sendNext:response];
                }
//                NSLog(@"refreshDataCommand subscriber sendCompleted");
                [subscriber sendCompleted];
            }];
            
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }];
    
    // 信号流：O-O-O-O-O-O，而下面这段就是,跳过第一个信号，并且只执行一次。
    [[[_refreshDataCommand.executing skip:1] take:1] subscribeNext:^(NSNumber * _Nullable x) {
//        NSLog(@"executing subscribeNext");
        [self showStatus:@"正在加载..."];
    }];
    
    // 进行业务处理
    [[[_refreshDataCommand executionSignals] switchToLatest] subscribeNext:^(NSDictionary*  _Nullable response) {
//        NSLog(@"switchToLatest subscribeNext");
        
        if (!response) {
             [self showErrorStatus:@"网络有问题！"];
            return;
        }
        
        // 把 BO 数据转成 VM
        NSMutableArray<CircleListMainViewCellViewModel*>*tempt = [NSMutableArray array];
        NSArray *subjects = [response valueForKey:@"subjects"];
        for (NSDictionary *object in subjects) {;
            CircleListMainViewCellViewModel *cellViewModel = [[CircleListMainViewCellViewModel alloc] init];
            cellViewModel.model = [DouBanTheatersModel yy_modelWithJSON:object];
            CircleListMainViewCellViewModel *cellViewModel1 = [[CircleListMainViewCellViewModel alloc] init];
            cellViewModel1.model = [DouBanTheatersModel yy_modelWithJSON:object];
            [tempt addObject:cellViewModel];
            [tempt addObject:cellViewModel1];
        }
        self.dataArray = [NSArray arrayWithArray:tempt];
        [self showMessage:@"请求成功！"];
    }];
    
    // 错误处理
    [_refreshDataCommand.errors subscribeNext:^(NSError * _Nullable x) {
//        NSLog(@"errors subscribeNext");
        [self showErrorStatus:@"网络有问题！"];
    }];
}
-(void)showMessage:(NSString*)message{
    [self.refreshDataSubject sendNext:@{@"code":@(RefreshUI),@"msg":message}];
}
-(void)showStatus:(NSString*)status{
    [self.refreshDataSubject sendNext:@{@"code":@(RefreshLoading),@"msg":status}];
}
-(void)showErrorStatus:(NSString*)error{
    [self.refreshDataSubject sendNext:@{@"code":@(RefreshError),@"msg":error}];
}

#pragma mark - getter
-(HttpManager *)httpManager{
    if (!_httpManager) {
        _httpManager = [[HttpManager alloc] initWithBaseURLString:@"https://api.douban.com"];
    }
    return _httpManager;
}
-(RACSubject *)refreshDataSubject{
    if (!_refreshDataSubject) {
        _refreshDataSubject = [RACSubject subject];
    }
    return _refreshDataSubject;
}

-(RACSubject *)cellClickSubject{
    if (!_cellClickSubject) {
        _cellClickSubject = [RACSubject subject];
    }
    return _cellClickSubject;
}
@end
